import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:go_router/go_router.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';

import '../providers/auth_provider.dart';
import '../providers/device_providers.dart';
import '../screens/home/home_page.dart';
import '../screens/home/multi_player_page.dart';
import '../screens/login_page.dart';

/// 路由路径常量（可选，提升可维护性）
abstract class AppRoute {
  static const String login = '/';
  static const String home = '/home';
  static const String play = '/play';
}

// 👇 创建全局 navigatorKey
final GlobalKey<NavigatorState> navigatorKey = GlobalKey<NavigatorState>();

/// 全局 GoRouter 实例
final GoRouter router = GoRouter(
  navigatorKey: navigatorKey,
  initialLocation: AppRoute.login,
  routes: [
    // 登录页
    GoRoute(
      path: AppRoute.login,
      name: 'Login',
      builder: (context, state) => const LoginPage(),
    ),
    // 主页（带 Tab 的容器）
    GoRoute(
      path: AppRoute.home,
      name: 'Home',
      builder: (context, state) => const HomePage(),
    ),
    // 播放页：/play/123
    GoRoute(
      path: '${AppRoute.play}/:deviceId',
      name: 'Play',
      builder: (context, state) {
        final deviceIdStr = state.pathParameters['deviceId']!;
        Widget goBack() {
          // 无效设备 ID，跳回首页
          if (context.mounted) {
            context.go(AppRoute.home);
          }
          return const SizedBox();
        }

        final deviceId = int.tryParse(deviceIdStr);
        if (deviceId == null) return goBack();
        final realContext = navigatorKey.currentContext;
        if (realContext == null) {
          return goBack();
        }

        final container = ProviderScope.containerOf(realContext);
        final device = container
            .read(deviceListProvider)
            .value
            ?.firstWhere((e) => e.id == deviceId);
        if (device == null) return goBack();

        return MultiPlayerPage(device: device);
      },
    ),
  ],
  redirect: (context, state) {
    // 👇 直接使用本地的 navigatorKey
    final realContext = navigatorKey.currentContext;
    if (realContext == null) return null;

    final container = ProviderScope.containerOf(realContext);
    final authAsync = container.read(authStateProvider);

    if (authAsync.isLoading) {
      return null;
    }

    final isLogged = authAsync.hasValue && authAsync.value != null;
    final isLoginPage = state.uri.path == AppRoute.login;

    if (!isLogged) {
      return isLoginPage ? null : AppRoute.login;
    } else {
      return isLoginPage ? AppRoute.home : null;
    }
  },
);
